package com.house.wym.controller;

import com.house.wym.entity.House;
import com.house.wym.entity.Staff;
import com.house.wym.service.IHouserService;
import com.house.wym.service.IStaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


//部分功能和admin重合。在AdminController里面
@Controller
public class StaffController {

	@Autowired
	private IStaffService service;

	@Autowired
	private IHouserService dao;

	/**
	 * 跳转到登录页
	 * 
	 * @return
	 */
	@RequestMapping("/toStaffLogin")
	public String toStaffLogin() {
		return "staff";
	}

	/**
	 * 登录
	 * 
	 * @param username
	 * @param userpwd
	 * @param req
	 * @return
	 */
	@RequestMapping("/staffAccess")
	@ResponseBody
	public String staffAccess(String username, String userpwd, HttpServletRequest req) {
		Staff staff = new Staff(username, userpwd);
		Staff staffAccess = service.staffAccess(staff);
		req.getSession().setAttribute("Staff", staffAccess);
		if (staffAccess != null)
			return "OK";
		return "FAIL";
	}

	/**
	 * 登出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/staffSingnout")
	public String signout(HttpServletRequest request) {
		request.getSession().invalidate();
		return "staff";
	}

	@RequestMapping("/toStaffHomePage")
	public String toStaffHomePage() {
		return "staffhome";
	}


	/**
	 * 跳转到管理员更新房源界面
	 * 
	 * @param hID
	 * @param request
	 * @return
	 */
	@RequestMapping("/toStaffUpdateHousePage")
	public String toUpdatePage(int hID, HttpServletRequest request) {
		House house = dao.findHouseDetailsById(hID);
		request.getSession().setAttribute("House", house);
		return "updatehouse";
	}



	@RequestMapping("/toUpdateStaffPwdPage")
	public String toUpdateStaffPwdPage() {
		return "updateStaffPwd";
	}


	@RequestMapping("/updateStaffPwd")
	@ResponseBody
	public String updateStaffPwd(HttpServletRequest request,String oldpwd, String newpwd, String newpwdagain) {
		Staff staff = new Staff();
		Staff staffSession = (Staff) request.getSession().getAttribute("Staff");
		staff.setId(staffSession.getId());
		staff.setUserpwd(oldpwd);
		Staff checkStaffPwd = service.checkStaffPwd(staff);
		if (checkStaffPwd == null) {
			return "ERROR";
		}
		if (!newpwd.equals(newpwdagain)) {
			return "FAIL";
		}
		Staff a = new Staff();
		a.setId(staffSession.getId());
		a.setUserpwd(newpwd);
		int n = service.updateStaffPwd(a);
		if (n > 0)
			return "OK";
		return "FAIL";
	}
}
